package org.example.mallweb.mallservice.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import org.example.mallcommon.exceptioninfo.LoginExceptionInfo;
import org.example.mallcommon.exceptioninfo.RegisterException;
import org.example.mallcommon.projo.User;
import org.example.mallcommon.result.ReturnResult;
import org.example.mallcommon.tool.JwtUtil;
import org.example.mallweb.mallservice.mybatiscommon.userprojo.UserMapper;
import org.example.mallweb.mallservice.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @author 韩先楚
 */
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;
    /**
     * 登录
     */
    @Override
    public ReturnResult<User> login(User user) {
        //查询是否有该用户
        User returnUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()).eq("password", user.getPassword()));
        if (returnUser == null)
            throw new LoginExceptionInfo("用户名或密码错误");
        //有则登录成功，并返回jwt信息,没有抛出异常

//        if (count == 0)
//            throw new LoginExceptionInfo("用户名或密码错误");
//
//            //Todo 登录成功逻辑
//        //防止多台设备登录
//        String jwt = jwtUtil.generateToken(user);
//        String uuid = UUID.randomUUID().toString();
//        //存入redis 时间为6小时
//        stringRedisTemplate.opsForValue().set(LoginConstant.LOGIN_TOKEN+uuid,jwt,6, TimeUnit.HOURS);
//        stringRedisTemplate.opsForValue().set(LoginConstant.LOGIN_USER_ID+user.getUsername(),uuid,6, TimeUnit.HOURS);
        return ReturnResult.success(returnUser);
    }

    @Override
    public void register(User user) {

            Long count = userMapper.selectCount(new QueryWrapper<User>().eq("username", user.getUsername()));
            if (count!=0)
            {
                throw new RegisterException("用户已存在");
            }
            userMapper.insert(user);
    }
}
